package com.lagou.edu.controller;

import com.lagou.edu.clinet.EmailClient;
import com.lagou.edu.dao.AuthCodeDao;
import com.lagou.edu.pojo.AuthCode;
import com.lagou.edu.service.ResumeService;
import com.lagou.edu.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.data.domain.Example;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/code")
public class AuthCodeController {

    @Autowired
    private AuthCodeDao authCodeDao;


    @Autowired
    private EmailClient emailClient;

    //"/resume/openstate/1545132"
    @GetMapping("/create/{email}")
    public String create(@PathVariable String email) {
        String code = RandomUtil.randomString(6);
        AuthCode authCode = new AuthCode();
        authCode.setCode(code);
        authCode.setEmail(email);

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime fiveMinLatter = now.plusMinutes(5);

        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdtNow = now.atZone(zoneId);
        ZonedDateTime zdtLatter = fiveMinLatter.atZone(zoneId);
        authCode.setCreatetime(Date.from(zdtNow.toInstant()));
        authCode.setExpiretime(Date.from(zdtLatter.toInstant()));
        authCodeDao.save(authCode);

        boolean isSend = emailClient.sendEmail(email, code);
        if (isSend) {
            return "发送成功";
        }

        return "发送失败";
    }


    @GetMapping("/validate/{email}/{code}")
    public int validate(@PathVariable String email,@PathVariable String code) {
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        Example<AuthCode> example = Example.of(authCode);
        List<AuthCode> list = authCodeDao.findAll(example);
        if (CollectionUtils.isEmpty(list)) {
            return 1;
        } else if (list.get(0).getExpiretime().before(new Date())) {
            return 2;
        } else {
            return 0;
        }
    }
}
